package com.clp.util.hutool.core.util;

import com.clp.util.hutool.core.io.FileUtil;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;

public class CharsetUtil {
    public static final String GBK = "GBK";

    public static final Charset CHARSET_UTF_8 = StandardCharsets.UTF_8;
    public static final Charset CHARSET_GBK;

    static {
        // 避免不支持GBK的系统中运行报错
        Charset _CHARSET_GBK = null;
        try {
            _CHARSET_GBK = Charset.forName(GBK);
        } catch (UnsupportedCharsetException e) {
            // ignore
        }
        CHARSET_GBK = _CHARSET_GBK;
    }

    /**
     * 转换为 Charset 对象，
     * @param charsetName 为空返回默认字符集
     * @return
     */
    public static Charset charset(String charsetName) {
        return StrUtil.isBlank(charsetName) ? Charset.defaultCharset() : Charset.forName(charsetName);
    }

    public static String systemCharsetName() {
        return systemCharset().name();
    }

    private static Charset systemCharset() {
        return FileUtil.isWindows() ? CHARSET_GBK : defaultCharset();
    }

    private static Charset defaultCharset() {
        return Charset.defaultCharset();
    }
}
